# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=openjpeg

pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.5.2
pkgrel=1
pkgdesc="An open source JPEG 2000 codec (mingw-w64)"
arch=('any')
url="http://www.openjpeg.org"
license=("BSD")
depends=("${MINGW_PACKAGE_PREFIX}-lcms2" "${MINGW_PACKAGE_PREFIX}-libtiff" "${MINGW_PACKAGE_PREFIX}-libpng" "${MINGW_PACKAGE_PREFIX}-zlib")
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc" "${MINGW_PACKAGE_PREFIX}-cmake" "${MINGW_PACKAGE_PREFIX}-pkg-config")
options=('staticlibs' 'strip')
source=(http://sourceforge.net/projects/openjpeg.mirror/files/${_realname}-${pkgver}.tar.gz
    "cdecl.patch"
    "openjpeg-1.5.1_tiff-pkgconfig.patch"
    mingw-install-pkgconfig-files.patch
    versioned-dlls-mingw.patch)

md5sums=('c41772c30fb1c272358b3707233134a1'
         '673edf457f9b4f3fdc9a083e1857a76a'
         '7d4244a290c6f8d6777a7bd68706a7ef'
         '5f1a6d346dad00f919723dbc00546ae1'
         'e68263246b76758903bfcc2c9de3601f')

prepare() {
  cd "$srcdir/openjpeg-$pkgver"
  # Fix CRLF line endings
  dos2unix libopenjpeg/opj_malloc.h
  #rm -r thirdparty
  patch -Np1 -i "$srcdir"/cdecl.patch
  patch -Np1 -i "$srcdir"/openjpeg-1.5.1_tiff-pkgconfig.patch
  patch -Np1 -i "$srcdir"/mingw-install-pkgconfig-files.patch
  patch -Np1 -i "$srcdir"/versioned-dlls-mingw.patch

  #autoreconf -i
}

build() {
  mkdir -p ${pkgdir}${MINGW_PREFIX}
  pushd ${pkgdir}${MINGW_PREFIX} > /dev/null
  export PREFIX_WIN=`pwd -W`
  popd > /dev/null
  
  pushd ${MINGW_PREFIX} > /dev/null
  export PREFIX_DEPS=`pwd -W`
  popd > /dev/null

  [[ -d $srcdir/build-${MINGW_CHOST} ]] && rm -rf $srcdir/build-${MINGW_CHOST}
  mkdir $srcdir/build-${MINGW_CHOST}
  cd $srcdir/build-${MINGW_CHOST}
  
  ${MINGW_PREFIX}/bin/cmake \
    -G"MSYS Makefiles" \
    -DCMAKE_INSTALL_PREFIX=${PREFIX_WIN} \
    -DCMAKE_BUILD_TYPE=Release \
    -DBUILD_TESTING:BOOL=ON \
    -DCMAKE_SYSTEM_PREFIX_PATH=${PREFIX_DEPS} \
    -DOPENJPEG_INSTALL_SUBDIR="openjpeg/${ver}" \
    -DBUILD_MJ2=ON \
    -DBUILD_JPWL=ON \
    -DBUILD_JPIP=ON \
    ../${_realname}-$pkgver
  make
}

package() {
  cd "$srcdir/build-${MINGW_CHOST}"
  make install # DESTDIR="$pkgdir"

  mkdir -p ${pkgdir}${MINGW_PREFIX}
  pushd ${pkgdir}${MINGW_PREFIX} > /dev/null
  export PREFIX_WIN=`pwd -W`
  popd > /dev/null
  sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" \
    -i ${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/libopenjpeg.pc \
    -i ${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/libopenjpeg1.pc

  # Fix conflict with openjpeg2
  mv ${pkgdir}${MINGW_PREFIX}/bin/opj_dec_server{,1}.exe
}
